package com.cardone.common.security.shiro.web.filter.authc;

import com.cardone.common.util.MapperUtils;
import com.cardone.common.util.ReturnDataUtils;
import com.cardone.context.CodeException;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.CharEncoding;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Writer;
import java.util.List;
import java.util.Map;

/**
 * Created by c100000002 on 15-1-9.
 */
@lombok.extern.slf4j.Slf4j
public class CardOneUserFilter extends UserFilter {
    /**
     * json路径集合
     */
    @Setter
    @Getter
    private List<String> jsonUrlList = Lists.newArrayList("/**/*.json", "/**/*.txt");

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String servletPath = com.cardone.common.util.WebUtils.getServletPath();

        if (!com.cardone.common.util.StringUtils.matchList(jsonUrlList, servletPath)) {
            saveRequestAndRedirectToLogin(request, response);

            return false;
        }

        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType("application/json");

        final Map<String, String> returnDataMap = ReturnDataUtils.newErrorMap(new CodeException("请登录系统"));

        try (Writer out = response.getWriter()) {
            out.write(MapperUtils.toJson(returnDataMap));
        }

        return false;
    }
}
